package com.smartao;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.smartao.core.security.exception.CaptchaAuthenticationException;
import com.smartao.core.security.exception.DynamicPasswdAuthenticationException;
import com.smartao.core.security.exception.UserDisabledException;
import com.smartao.core.security.exception.UserNotFoundException;
import com.smartao.core.security.exception.WrongPasswordException;

@Controller
@Scope("prototype")
public class LoginAction implements Action,Serializable {

	private static final long serialVersionUID = -6274225994574596215L;

	private String message;
	private String username;
	private String password;
	private static final Map<String, String> failureMessageMap = new HashMap<String, String>();

	static {
		failureMessageMap.put(CaptchaAuthenticationException.class.getName(), "验证码输入不正确!");
		failureMessageMap.put(DynamicPasswdAuthenticationException.class.getName(), "动态密码不正确！");
		failureMessageMap.put(UserNotFoundException.class.getName(), "你输入的帐号不存在！");
		failureMessageMap.put(WrongPasswordException.class.getName(), "你输入密码不正确！");
		failureMessageMap.put(UserDisabledException.class.getName(), "你的帐号已关闭！");
	}
	
	@Override
	public String execute() throws Exception {
		ActionContext context = ActionContext.getContext();
		Map<String, Object> session = context.getSession();
		Object exception = session.get(WebAttributes.AUTHENTICATION_EXCEPTION);
		if (exception != null) {
			exception = (AuthenticationException) exception;
			message = failureMessageMap.get(exception.getClass().getName());
			session.remove(WebAttributes.AUTHENTICATION_EXCEPTION);
		}

		//StringBuffer requestUrl = request.getRequestURL();
		//String baseUrl = requestUrl.substring(0, requestUrl.lastIndexOf("/"));

		//获取浏览器信息
		//String userAgentString = request.getHeader("User-Agent").toLowerCase();

		return "success";
	}

	public String getMessage() {
		return message;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
